<template>
  <el-dialog v-model="visible" :title="!dataForm.id ? '新增小区' : '编辑小区'" :close-on-click-modal="false" :close-on-press-escape="false" width="800px">
    <el-form :model="dataForm" :rules="rules" ref="dataFormRef" @keyup.enter="dataFormSubmitHandle()" label-width="120px">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="小区名称" prop="name">
            <el-input v-model="dataForm.name" placeholder="请输入小区名称"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="所属区域" prop="countyId">
            <el-select v-model="dataForm.countyId" placeholder="请选择区域" style="width: 100%">
              <el-option
                v-for="county in countyList"
                :key="county.id"
                :label="county.name"
                :value="county.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="主力户型" prop="type">
            <el-input v-model="dataForm.type" placeholder="如：1-3居室"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="服务电话" prop="number">
            <el-input v-model="dataForm.number" placeholder="请输入服务电话"></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="项目地址" prop="address">
        <el-input v-model="dataForm.address" placeholder="请输入详细地址"></el-input>
      </el-form-item>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="最低租金" prop="rentMin">
            <el-input-number
              v-model="dataForm.rentMin"
              :min="0"
              :precision="2"
              placeholder="最低租金"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="最高租金" prop="rentMax">
            <el-input-number
              v-model="dataForm.rentMax"
              :min="0"
              :precision="2"
              placeholder="最高租金"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="房屋总数" prop="totalHouses">
            <el-input-number
              v-model="dataForm.totalHouses"
              :min="0"
              placeholder="房屋总数"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="楼栋总数" prop="totalBuildings">
            <el-input-number
              v-model="dataForm.totalBuildings"
              :min="0"
              placeholder="楼栋总数"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="状态" prop="delFlag">
            <el-select v-model="dataForm.delFlag" placeholder="请选择状态" style="width: 100%">
              <el-option label="正常" :value="0" />
              <el-option label="已删除" :value="1" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="开盘时间" prop="listTime">
        <el-date-picker
          v-model="dataForm.listTime"
          type="datetime"
          placeholder="选择开盘时间"
          style="width: 100%"
          format="YYYY-MM-DD HH:mm:ss"
          value-format="YYYY-MM-DD HH:mm:ss"
        />
      </el-form-item>

      <el-form-item label="配套设施" prop="assort">
        <el-input
          v-model="dataForm.assort"
          type="textarea"
          :rows="3"
          placeholder="请输入配套设施信息"
        />
      </el-form-item>

      <el-form-item label="项目简介" prop="brief">
        <el-input
          v-model="dataForm.brief"
          type="textarea"
          :rows="4"
          placeholder="请输入项目简介"
        />
      </el-form-item>

      <el-form-item label="小区图片" prop="ossUrls">
        <el-input
          v-model="dataForm.ossUrls"
          type="textarea"
          :rows="2"
          placeholder="请输入图片URL，多张图片用逗号分隔，最多3张"
        />
        <div class="upload-tip">
          <p>支持直接输入图片URL地址，多张图片用英文逗号分隔</p>
        </div>
      </el-form-item>
    </el-form>
    <template v-slot:footer>
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmitHandle()">确定</el-button>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { reactive, ref, onMounted } from "vue";
import baseService from "@/service/baseService";
import { ElMessage } from "element-plus";

const emit = defineEmits(["refreshDataList"]);

const visible = ref(false);
const dataFormRef = ref();
const countyList = ref<any[]>([]);

const dataForm = reactive({
  id: "",
  name: "",
  countyId: "",
  type: "",
  listTime: "",
  number: "",
  address: "",
  brief: "",
  userId: "",
  enterpriseId: "",
  rentMin: 0,
  rentMax: 0,
  assort: "",
  totalHouses: 0,
  selectedHouses: 0,
  totalBuildings: 0,
  ossUrls: "",
  delFlag: 0,
});

const rules = ref({
  name: [
    { required: true, message: '请输入小区名称', trigger: 'blur' }
  ],
  countyId: [
    { required: true, message: '请选择所属区域', trigger: 'change' }
  ],
  address: [
    { required: true, message: '请输入项目地址', trigger: 'blur' }
  ]
});

// 获取区域列表
const getCountyList = async () => {
  try {
    const res = await baseService.get("/rental/areacounty/getAllCounty");
    if (res.code === 0) {
      countyList.value = res.data || [];
    }
  } catch (error) {
    console.error('获取区域列表失败:', error);
  }
};

const init = (id?: number) => {
  visible.value = true;

  // 重置表单数据
  Object.assign(dataForm, {
    id: "",
    name: "",
    countyId: "",
    type: "",
    listTime: "",
    number: "",
    address: "",
    brief: "",
    userId: "",
    enterpriseId: "",
    rentMin: 0,
    rentMax: 0,
    assort: "",
    totalHouses: 0,
    selectedHouses: 0,
    totalBuildings: 0,
    ossUrls: "",
    delFlag: 0,
  });

  // 重置表单验证
  if (dataFormRef.value) {
    dataFormRef.value.resetFields();
  }

  if (id) {
    getInfo(id);
  }
};

// 获取信息
const getInfo = (id: number) => {
  baseService.get("/rental/areaplot/" + id).then((res) => {
    Object.assign(dataForm, res.data);
  });
};

// 表单提交
const dataFormSubmitHandle = () => {
  dataFormRef.value.validate((valid: boolean) => {
    if (!valid) {
      return false;
    }

    // 数据处理
    const submitData = { ...dataForm };

    // 确保数值类型正确
    submitData.rentMin = Number(submitData.rentMin) || 0;
    submitData.rentMax = Number(submitData.rentMax) || 0;
    submitData.totalHouses = Number(submitData.totalHouses) || 0;
    submitData.totalBuildings = Number(submitData.totalBuildings) || 0;
    submitData.delFlag = Number(submitData.delFlag) || 0;

    (!dataForm.id ? baseService.post : baseService.put)("/rental/areaplot", submitData).then((res) => {
      ElMessage.success({
        message: "操作成功",
        duration: 500,
        onClose: () => {
          visible.value = false;
          emit("refreshDataList");
        }
      });
    });
  });
};

// 组件挂载时获取区域列表
onMounted(() => {
  getCountyList();
});

defineExpose({
  init
});
</script>

<style scoped>
.upload-tip {
  margin-top: 8px;
}

.upload-tip p {
  font-size: 12px;
  color: #999;
  margin: 0;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}

:deep(.el-input-number) {
  width: 100%;
}
</style>